package mytest.ssw.www.myandroidproject.activity;


import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.util.SparseLongArray;
import android.view.View;
import android.widget.TextView;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;

import java.io.File;
import java.lang.reflect.Field;

import mytest.ssw.www.myandroidproject.AnalysisJson.AnalysisJ;
import mytest.ssw.www.myandroidproject.R;
import mytest.ssw.www.myandroidproject.mydate.CheckUpdateInfo;
import mytest.ssw.www.myandroidproject.thread.SimplePostThread;
import mytest.ssw.www.myandroidproject.thread.ThreadPoolUtils;

public class SplashActivity extends AppCompatActivity {

    private String downloadurl = "";
    private String updateurl = "http://115.28.144.181/updateurl.html";
    TextView versionTextview, descriptionTextview, loadupdateTextview;
    String version;
    final int entermainactivity = 1;
    final int installapk = 6;
    final int enterupdate = 2;
    SharedPreferences sp;
    boolean updatestate;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
        versionTextview = (TextView) findViewById(R.id.VersionTextview);
        descriptionTextview = (TextView) findViewById(R.id.DescriptionTextview);
        loadupdateTextview = (TextView) findViewById(R.id.loadupdatetextview);
        //checksd();
        //获版本信息
        version = Getversioninfo();
        sp = getSharedPreferences("updatecinfig", MODE_PRIVATE);
        Log.v("version", version);
        updatestate=sp.getBoolean("update", true);
        if (updatestate) {
            checkUpdate();
        } else {
            mhandler.sendEmptyMessageDelayed(entermainactivity, 2000);

        }

    }

    public void checkUpdate() {
        final long starttime = System.currentTimeMillis();
        SimplePostThread simplePostThread = new SimplePostThread(updateurl);
        final Message msg = Message.obtain();
        simplePostThread.setStringback(new SimplePostThread.stringBack() {
            @Override
            public void getbackstr(String result) {
                //得到请求后的结果
                try {
                    Log.v("result", result);
                    CheckUpdateInfo checkUpdateInfo = new CheckUpdateInfo();
                    AnalysisJ analysisJ = new AnalysisJ();
                    checkUpdateInfo = analysisJ.AnalysisCheckUpdate(result);
                    if (checkUpdateInfo != null) {
                        if (!version.equals(checkUpdateInfo.getVersion())) {//进入升级
                            Log.v("2.0", "更新更好用的版本");
                            downloadurl = checkUpdateInfo.getApkurl();
                            msg.what = enterupdate;
                        } else {
                            //进入主页
                            msg.what = entermainactivity;
                        }

                    } else //获取新版本失败
                    {
                        msg.what = entermainactivity;
                    }
                } catch (Exception e) {
                } finally {
                    long Endtime = System.currentTimeMillis();
                    if ((starttime - Endtime) < 3000 && msg.what != enterupdate) {
                        //时间不够,延时进入
                        mhandler.sendEmptyMessageDelayed(msg.what, (3000 - (starttime - Endtime)));
                    } else {//
                        mhandler.sendMessage(msg);
                    }
                }
            }
        });
        //将线程放入线程池中
        ThreadPoolUtils.execute(simplePostThread);


    }


    public void Downloadapk() {   //检查sd卡是否挂载
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            //sd存在
            FinalHttp finalHttp = new FinalHttp();
            finalHttp.download(downloadurl, Environment.getExternalStorageDirectory().getAbsolutePath() + "/ceshi/app.apk", new AjaxCallBack<File>() {
                @Override
                public void onLoading(long count, long current) {
                    super.onLoading(count, current);
                    Log.v("onLoading", "onLoading");
                    loadupdateTextview.setText("升级进度" + current / count * 100 + "%");
                }

                @Override
                public void onSuccess(File file) {
                    super.onSuccess(file);
                    Log.v("onSuccess", "onSuccess");
                    Installapk(file);
                }

                @Override
                public void onStart() {
                    super.onStart();
                    Log.v("onStart1", "onStart");
                }

                @Override
                public AjaxCallBack<File> progress(boolean progress, int rate) {
                    return super.progress(progress, rate);
                }

                @Override
                public int getRate() {
                    return super.getRate();
                }

                @Override
                public boolean isProgress() {
                    return super.isProgress();
                }

                @Override
                public void onFailure(Throwable t, int errorNo, String strMsg) {
                    super.onFailure(t, errorNo, strMsg);
                    Log.v("onFailure", strMsg);
                }
            });

        }
    }

    /*

    获取版本号
     */
    public String Getversioninfo() {
        PackageManager packagemagege = this.getPackageManager();
        try {
            PackageInfo pinfo = packagemagege.getPackageInfo(this.getPackageName(), 0);
            return pinfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }

    //进入主页面的方法
    public void EnterMainactivity() {
        if (true) {
            Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent);
            finish();
        } else {
        }
    }

    Handler mhandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case entermainactivity: {
                    //进入主页面
                    EnterMainactivity();
                    break;
                }
                case enterupdate: {
                    AlertDialog.Builder updatedialog = new AlertDialog.Builder(SplashActivity.this);
                    updatedialog.setTitle("有新版本");
                    updatedialog.setMessage("速度升级");
                    updatedialog.setCancelable(false);
                    updatedialog.setPositiveButton("进行升级", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Downloadapk();
                        }
                    });
                    updatedialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            EnterMainactivity();
                        }
                    });
                    updatedialog.show();
                    break;
                }
            }


        }
    };


    public void Installapk(File t) {
        String uristr = Environment.getExternalStorageDirectory().getAbsolutePath() + "/ceshi/app.apk";
        Uri uri = Uri.parse(uristr);
        // 创建Intent意图
        Intent intent = new Intent(Intent.ACTION_VIEW);
        // 设置Uri和类型
        intent.setDataAndType(Uri.fromFile(t), "application/vnd.android.package-archive");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        // 执行意图进行安装
        startActivity(intent);
    }


    @Override
    protected void onResume() {
        super.onResume();
        //   EnterMainactivity();
    }
}
